package com.tao.picture.ui.person.viewmodel

import android.app.Application
import android.net.Uri
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.tao.BaseViewModel
import com.tao.data.Resource
import com.tao.di.getTaskManager
import com.tao.net.download.download
import com.tao.net.request
import com.tao.picture.ui.person.data.entity.Person
import com.tao.picture.ui.person.data.repository.ImageRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class PersonViewModel @Inject constructor(
    private val repository: ImageRepository,
    application: Application
) : BaseViewModel(application) {

    val person: MutableLiveData<Resource<List<Person>>> = MutableLiveData()
    val person2: MutableLiveData<List<Person>> = MutableLiveData()
    val img: MutableLiveData<Resource<Uri>> = MutableLiveData()

    /**
     * 获取图片
     */
    fun getImage() {
        request(repository.getImages(), person)
    }

    /**
     * 另一种请求方式 without fow，回调在view model中方便二次封装数据，如果数据不正规，flow的请求也可以做同样的修改
     * https://www.cnblogs.com/sw-code/p/15591713.html
     */
    fun getImage2() {
        request({ repository.getImages2() },
            onSuccess = {
                person2.value = it
            })
    }

    /**
     * 保存到db
     */
    fun saveImage(people: List<Person>) {
        viewModelScope.launch {
            repository.saveImages(people).collect()
        }
    }

    fun saveImage(person: Person) {
        viewModelScope.launch {
            // 流是冷的，如果不collect,将不会执行
            repository.saveImage(person).collect()
        }
    }

    /**
     * 下载文件
     */
    fun download() {
        download("https://img2.baidu.com/it/u=2102736929,2417598652&fm=26&fmt=auto&gp=0.jpg", img)
    }

    fun downloadImg() {
        download("http://gank.io/images/7fa98787d009465a9d196fbff6b0a5d7", img, ".jpg")
    }

    /**
     * 取消下载
     */
    fun cancel() {
        getTaskManager().cancel("https://img2.baidu.com/it/u=2102736929,2417598652&fm=26&fmt=auto&gp=0.jpg")
    }

}